/**  
 * @author renbangjie renbangjie@126.com  
 * @date 2015-8-28 下午2:40:39
 * @version V1.0  
 * <b>Copyright (c)</b> 2014医信金融信息服务（上海）有限公司-版权所有<br/>
 */
package com.yjd.comm.formater;

import java.text.ParseException;
import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.format.Formatter;

import com.yjd.comm.util.DateUtil;

/**
 * 字符串转时间戳
 * 
 * @author renbangjie renbangjie@126.com
 * @date 2015-8-28 下午2:40:39
 */
public final class DateFormatter implements Formatter<String> {

	private String pattern;

	private String target;

	public DateFormatter(String pattern) {
		this.pattern = pattern;
	}

	public DateFormatter(String pattern, String target) {
		this.pattern = pattern;
		this.target = target;
	}

	@Override
	public String print(String date, Locale locale) {
		if (StringUtils.isBlank(date)) {
			return "";
		}
		if (StringUtils.isBlank(target)) {
			return String
					.valueOf(DateUtil.dateStringToTimestamp(date, pattern));
		}
		return DateUtil.timestampToDateString(DateUtil.dateStringToTimestamp(
				date, DateUtil.PATTERN_yyyyMMdd), DateUtil.PATTERN_yyyy_MM_dd);
	}
	
	
	@Override
	public String parse(String date, Locale locale) throws ParseException {
		if (StringUtils.isBlank(date) || "null".equals(date)) {
			return "";
		}
		if (NumberUtils.isNumber(date) || StringUtils.isBlank(target)) {
			return DateUtil.timestampToDateString(Long.valueOf(date), pattern);
		}
		return DateUtil
				.timestampToDateString(DateUtil.dateStringToTimestamp(date,
						DateUtil.PATTERN_yyyy_MM_dd), DateUtil.PATTERN_yyyyMMdd);
	}
}
